package com.letme.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.letme.store.domain.MallCitys;
import com.letme.store.domain.vo.CityTreeVo;
import com.letme.store.mapper.MallCitysMapper;
import com.letme.store.service.MallCitysService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author lock-xq
 * @Date 2025/9/12 11:20
 **/
@Service
public class MallCitysServiceImpl extends ServiceImpl<MallCitysMapper, MallCitys> implements MallCitysService {

    @Override
    public List<MallCitys> queryCityList(String fatherCode) {
        return this.list(new LambdaQueryWrapper<MallCitys>().eq(MallCitys::getFatherCode,fatherCode));
    }

    @Override
    public List<CityTreeVo> cityTree() {
        List<MallCitys> citysList = this.list(new LambdaQueryWrapper<MallCitys>().select(MallCitys::getAddrCode,MallCitys::getAddrName,MallCitys::getFatherCode,MallCitys::getType));
        List<CityTreeVo> list = citysList.stream().map(e -> new CityTreeVo(e.getAddrCode(), e.getAddrName(),e.getFatherCode(),e.getType())).collect(Collectors.toList());
        List<CityTreeVo> listTree = new ArrayList<>();
        for (CityTreeVo vo : list){
            if("01".equals(vo.getType())){
                vo.setChildren(buildCityTree(list,vo.getAddrCode()));
                listTree.add(vo);
            }
        }
        return listTree;
    }

    //构建前端需要的树形结构
    public List<CityTreeVo> buildCityTree(List<CityTreeVo> treeList,String code){
        List<CityTreeVo> collect = treeList.stream().filter(m -> m.getFatherCode().equals(code)).collect(Collectors.toList());
        collect.stream().forEach(m->m.setChildren(getChildren(m,treeList)));
        return collect;
    }

    //构建子节点
    private List<CityTreeVo> getChildren(CityTreeVo tree, List<CityTreeVo> treeList) {
        List<CityTreeVo> collect = treeList.stream().filter(m -> m.getFatherCode().equals(tree.getAddrCode())).collect(Collectors.toList());
        collect.stream().forEach(m->m.setChildren(getChildren(m,treeList)));
        return collect;
    }
}
